
package com.yimixian.app.order;

import com.yimixian.app.R;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.model.Metadata;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

public class OrderInfoView extends LinearLayout {

    public OrderInfoView(Context context) {
        super(context);
        initOrderInfoView();
    }

    public OrderInfoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initOrderInfoView();
    }

    public OrderInfoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initOrderInfoView();
    }

    private void initOrderInfoView() {
        setOrientation(VERTICAL);
    }

    public void bind(List<Metadata> metadataList) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        for (final Metadata metadata : metadataList) {
            FrameLayout infoItemView = (FrameLayout) inflater.inflate(R.layout.order_info_item,
                    this, false);
            ((TextView) infoItemView.getChildAt(0)).setText(metadata.name);
            final TextView textView = (TextView) infoItemView.getChildAt(1);
            textView.setText(metadata.value);
            if (!TextUtils.isEmpty(metadata.url)) {
                textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
                textView.getPaint().setAntiAlias(true); // 抗锯齿
                textView.setTextColor(0xff008aff);
                textView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (metadata.url.contains("phone_number")) {
                            String url[] = metadata.url.split("phone_number=");
                            if (url.length == 2) {
                                Intent intentContact = new Intent(Intent.ACTION_CALL);
                                intentContact.setAction(Intent.ACTION_DIAL);
                                intentContact.setData(Uri.parse("tel:" + url[1]));
                                getContext().startActivity(intentContact);
                            }
                        } else {
                            Intent intent = new Intent(getContext(), WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_URL, metadata.url);
                            getContext().startActivity(intent);
                        }
                        textView.setTextColor(0xff999999);
                    }
                });
            }
            addView(infoItemView);
        }
    }
}
